package per.qiao.simplechian.core;


import per.qiao.simplechian.bo.NodeParam;
import per.qiao.simplechian.bo.NodeResult;

import java.util.Collections;
import java.util.List;

/**
 * 责任链上下文, 同时也是入口
 *
 * @author: qiaoyp
 * @Date: 2024/8/21 18:50
 * @Description:
 */
public class NodePipeline<T extends DefaultNode> implements PipelineActuator {

    /**
     * 头结点
     */
    private DefaultNode head;

    /**
     * 尾结点
     */
    private DefaultNode tail;

    /**
     * 当前链条的名称
     */
    private String name;

    public NodePipeline(String name) {
        this.name = name;
    }

    public void init(List<T> nodes) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }
        // 节点子节排序
        Collections.sort(nodes);
        this.head = null;
        this.tail = null;

        // 构建双链表
        for (T node : nodes) {
            if (this.head == null) {
                this.head = node;
                this.tail = node;
            } else {
                this.addLast(node);
            }
        }
    }

    /**
     * 添加头结点
     * @param node
     * @return
     */
    public NodePipeline<T> addFirst(T node) {
        if (this.head != null) {
            node.next(this.head);
            this.head.pre(node);
        } else {
            this.tail = node;
        }
        this.head = node;
        return this;
    }

    /**
     * 添加尾结点
     * @param node
     * @return
     */
    public NodePipeline<T> addLast(T node) {
        if (this.tail != null) {
            node.pre(this.tail);
            this.tail.next(node);
        } else {
            this.head = node;
        }
        this.tail = node;
        return this;
    }

    /**
     * 执行责任链-入口
     * @param nodeParam
     * @param result
     * @return
     */
    @Override
    public NodeResult exec(NodeParam nodeParam, NodeResult result) {
        if (head == null) {
            return result;
        }
        return this.head.exec(nodeParam, result);
    }
}
